package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.entity.vo.web.Catalog2Vo;
import com.atguigu.gulimall.product.service.CategoryService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @RequestMapping({"/","index.html"})
    public String index(Model model){

        //获取一级分类
        List<CategoryEntity> live1Category = categoryService.getLive1Categorys();
        model.addAttribute("categorys",live1Category);

        return "index";
    }

    @ResponseBody
    @RequestMapping("index/json/catalog.json")
    public Map<String,List<Catalog2Vo>> getCatalogJson(){

        Map<String,List<Catalog2Vo>> map = categoryService.getCatalogJson();

        return map;
    }

    @ResponseBody
    @RequestMapping("hello")
    public String hello(){

        //获取一个锁
        RLock lock = redisson.getLock("my-lock");

        //加锁
        //1.锁的自动续期，如果业务时间超长，运行期间自动给锁续上新的30秒，不用担心业务时间长，锁自动过期被删除
        //2.加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30秒后自动删除
//        lock.lock();//阻塞式等待，默认加的锁是30s时间,有看门狗机制，看门狗续期时间是锁超时时间的1/3

//        lock.lock(30, TimeUnit.SECONDS);//手动设置解锁时间，时间一定要大于业务时间，无看门狗机制
        //1.手动设置时间后，在锁时间到了，不会自动续期

        //最佳实站
        lock.lock(30, TimeUnit.SECONDS);//省去整个续期操作，如果业务时间超过30秒，这样的业务基本是有问题的

        try {
            System.out.println("枷锁成功，执行业务"+Thread.currentThread().getId());
        }catch (Exception e){

        }finally {
            //解锁
            System.out.println("释放锁" + Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }
}
